﻿using System;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.Windows;
using System.Xml.Linq;
using System.Xml;
using System.Linq;

namespace GlyphMaster
{
    public class GlyphProvider
    {
        public GlyphCollection collection;
        private Random rnd = new Random(DateTime.Now.Millisecond);
        private IEnumerable<XAttribute> _groups;
        private Int32 currentIndex;
        XDocument doc;

        #region constructors
        public GlyphProvider() // for testing purposes only
        {
        }

        public GlyphProvider(String localXML)
        {
            XmlReader reader = XmlReader.Create(localXML);
            reader.Read();
            doc = XDocument.Load(reader);
            _groups = (from charGroup in doc.Elements("characterset")
                          select charGroup).Elements("group").Attributes("value");
        }

        public GlyphProvider(Uri onlineXML)
        {
        }
        #endregion

        #region functions
        public void LoadGlyphs()
        {
            LoadGlyphs(null);
        }
        public void LoadGlyphs(String[] groupNames)
        {
            if (groupNames == null)
            {
                groupNames = _groups.Select(group => group.Value).ToArray();
            }
            collection = new GlyphCollection(doc.Element("characterset").Element("description").Value);
            foreach (String groupName in groupNames)
            {
                var characters = (from charGroup in doc.Element("characterset").Elements("group")
                                  where charGroup.Attribute("value").Value == groupName
                                  select charGroup).Elements("character");
                foreach (XElement character in characters)
                {
                    Glyph glyph = new Glyph(character.Element("ascii").Value, character.Element("glyph").Value, character.Element("image").Value, character.Element("description").Value);
                    glyph.collectionID = groupName;
                    collection.Add(glyph);
                }
            }
        }
        public Glyph GetNext()
        {
            if (collection.Count > 0)
            {
                currentIndex = rnd.Next(0, collection.Count);
                return collection[currentIndex];
            }
            else
            {
                return new Glyph("<null>", "<null>", null, "<null>");
            }
        }
        #endregion

        # region properties
        public Int32 size
        {
            get
            {
                return collection.Count;
            }
        }
        public String[] groups
        {
            get
            {
                return _groups.Select(group =>group.Value).ToArray();
            }
        }
        #endregion
    }
}
